<?php
/**
 * Created by PhpStorm.
 * Author: 黑瞎子
 * Date: 2018/3/18
 * Time: 22:58
 */

namespace app\api\controller\v1;


use app\api\controller\BaseCotroller;
use app\api\model\UserAddress;
use app\api\validate\AddressNew;
use app\api\service\Token as TokenService;
use app\api\model\User as UserModel;
use app\lib\enum\ScopeEnum;
use app\lib\exception\ForbiddenException;
use app\lib\exception\ParameterException;
use app\lib\exception\SuccessMessage;
use app\lib\exception\TokenException;
use app\lib\exception\UserException;
use think\Controller;

class Address extends BaseCotroller
{
    //前置操作-用户权限验证
    protected $beforeActionList = [
        'checkPrimaryScope' => ['only' => 'createOrUpdateAddress,getUserAddress']
    ];

    /*
     * 添加或更新用户地址
     * @url /address
     * 根据token来获取uid
     * 根据uid查找用户数据，判断用户是否存在，如果不存在则抛出异常
     * 获取用户从客户端提交来的地址信息
     * 根据用户地址信息是否存在，判断是添加地址还是更新地址
     * */
    public function createOrUpdateAddress(){
        $validate = new AddressNew();
        $validate->goCheck();

        $uid = TokenService::getCurrentUid();
        $user = UserModel::get($uid);
        if (!$user){
            throw new UserException();
        }
        $dateArray = $validate->getDateByRule(input('post.'));
        $userAddress = $user->address;
        if (!$userAddress){
            $user->address()->save($dateArray);
        }else{
            $user->address->save($dateArray);
        }
        //return $user;  //返回更新后的user信息，如果不需要完整信息，只需要提示信息更新成功，则
        return json(new SuccessMessage(), 201);
    }

    //获取用户地址
    public function getUserAddress(){
        $uid = TokenService::getCurrentUid();
        $address = UserAddress::where('user_id', '=', $uid)->find();
        if (!$address){
            throw new ParameterException([
                'msg' => '用户地址不存在'
            ]);
        }
        return $address;
    }
}